<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\model\Sms;
use App\Http\model\Curdpost;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\User;
use Illuminate\Support\Facades\Cache;

class LoginController extends BaseController
{
    /**
     * 登录信息接口
     * by 吉星
     */
    // 登录获取验证码
    public function code(Request $request){
        $arr = [];
        if(empty($request['phone'])){
            $arr['code'] = 1004;
            $arr['message'] = "手机号不能为空";
        }else{
            $phone = $request['phone'];
            // dump($com);
            // dump($company_data);exit;
            $num = rand(1111,9999);
            $msg = "验证码:".$num."，有效期3分钟【时代出行】";
            $code = new Sms();
            $re = $code -> sendSMS($phone,$msg);
            $data = json_decode($re,true);
            //  dump($data);

            if($data['error'] == 0){
                $arr['code'] = 1000;
                $arr['m_code'] = $num;
                $arr['message'] = '请求成功';
            }else{
                $arr['code'] = 1002;
                if($data['msg'] == 'FREQUENCE_ERROR'){
                    $arr['message'] = '请勿点击太快!';
                }else{
                    $arr['message'] = $data['msg'];
                }
            }
            Cache::set('M_CODE',$num,3600);
            Cache::set('PHONE',$phone,3600);
        }
        return $arr;
    }
    // 验证登录
    public function login(Request $request){
        //极光推送吗 放到 Cache里
        // 验证码 手机号判断
        $arr = [];
        if($request['phone']){
            $data = $request->query();
            $jiguangcode = $data['jiguangcode']; //激光码
            // dump(Cache::get('M_CODE'));
            $m_code = $data['m_code']; //验证码
            $session_code = Cache::get('M_CODE');
            $phone = Cache::get('PHONE');
            if($session_code == $m_code && $phone == $data['phone']){
                Cache::forget('M_CODE');
                Cache::forget('PHONE');
                $data['phone'] = $data['phone'];
                $re = Db::table('social_user')->where('phone',$data['phone'])->first();
                $re =  json_decode(json_encode($re),true);
                if($re && $re['is_delete'] !=1){
                    // dump(1111);
                    $user['jpush_code'] = $jiguangcode;
                    $user['model_status'] = $data['model_status'];
                    $save = Db::table('social_user')->where('phone',$data['phone'])->update($user);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                }elseif($re && $re['is_delete'] ==1){
                    // dump(2222);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $user['company_id'] = '';
                    $user['limit_rule_id'] = '';
                    $user['is_delete'] = 0;
                    $user['jpush_code'] = $jiguangcode;
                    $user['model_status'] = $data['model_status'];
                    $user['token'] = $token;
                    $save = Db::table('social_user')->where('phone',$data['phone'])->update($user);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                }else{
                    // dump(333);
                    $insetArr = [
                        'phone'=>$data['phone'],
                        'jpush_code'=>$jiguangcode,
                        'model_status'=>$data['model_status']
                    ];
                    $id = Db :: table('social_user')->insertGetId($insetArr);
                    if($id){
                        // dump(444);
                        $news = new Curdpost();
                        $array = ['CompanyId'=>'test','RegisterDate'=>date("Ymd",time()),'PassengerPhone'=>$data['phone'],'State'=>'0','Flag'=>1,'UpdateTime'=>date("YmdHis",time())];
                        $sqlwhere = "PassengerPhone = ".$data['phone'];
                        $list = $news->selectArr("passenger",$sqlwhere);
                        dump($list['code']);
                        if($list['code']==1000){
                            $add = $news->NewUpdate("passenger",$array,$sqlwhere);
                        }else{
                            $add = $news->NewInsert("passenger",$array);
                        }
                        
                        dump($add);
                    }
                    $users = User::where('id',$id)->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                    $user['token'] = $token;
                    $save = Db::table('social_user')->where('id',$id)->update($user);
                }
                $arr['code'] = 1000;
                $arr['message'] = '登录成功';
            }else{
                $arr['code'] = 1002;
                $arr['message'] = '登录失败,验证码不正确';
            }    
            // dump($users);
        }else{
            $arr['code'] = 1001;
            $arr['message'] = '登录失败,手机号不能为空';
        }
        
        return $arr;
    }
    // 注册协议
    public function xieyi(Request $request){
        if($request){
            return redirect('login/xieyi');
            // return redirect('http://www.baidu.com');
        }
    }
    // 个人中心以及侧边栏页面赋值
    public function userinfo(Request $request){
        $user_id = $request->get('id') ? $request->get('id') : '';
        $data = [];
        if($user_id){
            $user = Db::table('social_user as a')
                ->where('a.id','=',$user_id)
                ->select('a.id','a.nickname','a.picture','a.phone')
                ->first();
            $user = json_decode(json_encode($user),true);
            $user['id'] = (string)$user['id'];
            if($user){
                // 备注: id => 用户id nickname => 用户名称 picture=> 头像 phone=>手机号
                $res = ['code'=>1000,'message'=>"获取数据成功",'data'=>$user];
            }else{
                $res = ['code'=>1001,'message'=>"没有找到要查询的数据",'data'=>$data];
            }
        }else{
            $res = ['code'=>1002,'message'=>"参数错误",'data'=>$data];
        }
        return $res;
    }
    // 编辑资料页面赋值
    public function edit(Request $request){
        $uid = $request->get('id') ? $request->get('id') : '';
        $data = [];
        if($uid){
            $user = Db::table('social_user')
                ->where('id',$uid)
                ->select('id','nickname','picture','phone','sex')
                ->first();
            $user = json_decode(json_encode($user),true);
            $user['sex'] = (string)$user['sex'];
            if($user){
                // 备注: id => 用户id nickname => 用户名称 picture=> 头像 phone=>手机号 sex=>性别
                $res = ['code'=>1000,'message'=>"获取数据成功",'data'=>$user];
            }else{
                $res = ['code'=>1001,'message'=>'没有找到要查询的数据','data'=>$data];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误','data'=>$data];
        }
        return $res;
    }
    // 编辑资料提交
    public function post_edit(Request $request){
        $uid = $request->get('id') ? $request->get('id') : '';
        if($uid){
            $dat = $request->query();
            $data = array_splice($dat,1);
            $file = $request->file('file');//获取个人头像照片
            $info = Db::table('social_user')
                ->where('id',$uid)
                ->first();
            $info = json_decode(json_encode($info),true);
            // return $file;
            // dd($file);
            $data['sex'] = !empty($data['sex']) ? $data['sex'] : $info['sex'];
            $data['nickname'] = !empty($data['nickname']) ? $data['nickname'] : $info['nickname'];
            //return $file;
            if (!empty($file)) {
                $file_path = 'uploads/' . date("Ymd") . "/";
                $extension = $file->getClientOriginalExtension();//上传文件的后缀.
                $file_name = md5(time() . mt_rand(10, 99)) . '.' . $extension;
                $info = $file->move($file_path, $file_name);
                // return $info;
                if (!$info) {
                    $error = $file->getError();
                    return ['code'=>1004,'message'=>$error];
                    exit;
                }
                $data['picture'] = $file_path . $file_name;
                // dd($data);
            }
            $save = Db::table('social_user')->where('id','=',$uid)->update($data);
            if($save){
                $res = ['code'=>1000,'message'=>'修改成功!'];
            }else{
                $res = ['code'=>1001,'message'=>'修改失败,没有数据发生变化!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }

    // 投诉页面赋值
    public function complaints(Request $request){
        $uid = $request->get('id') ? $request->get('id') : '';
        $order_number = isset($request['order_number']) ? $request['order_number'] : false; //订单编号
        if($uid){
            if($order_number){
                // 根据订单编号查找订单信息
                $order = DB::table("order as a")
                    ->join('server_item as b','a.typeid','=','b.id','left')
                    ->where('a.id',$order_number)
                    ->select("a.usetime",'b.name','a.original','a.end','a.num')
                    ->first();
                $order = json_decode(json_encode($order),true);
                $order['time'] = date("m",$order['usetime']).'月'.date("d",$order['usetime']).'日 '.date("H:i",$order['usetime']);
                if($order){
                    $res = ['code'=>1000,'message'=>'获取数据成功!','data'=>$order];
                }else{
                    $res = ['code'=>1001,'message'=>'获取数据失败!'];
                }
            }else{
                $res = ['code'=>1003,'message'=>'没有找到订单编号!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }
    // 投诉提交
    public function complaints_post(Request $request){
        $uid = $request->get('id') ? $request->get('id') : '';
        $order_number = isset($request['order_number']) ? $request['order_number'] : false;
        $contents = isset($request['contents']) ? $request['contents'] : false;
        $beizhu = isset($request['beizhu']) ? $request['beizhu'] : false;
        if($uid){
            if($order_number){
                // 根据订单编号查找司机
                $driver = DB::table("order as a")
                    ->join('order_extend as b','a.extendid','=','b.id')
                    ->where('a.id',$order_number)
                    ->first();
                $driver = json_decode(json_encode($driver),true);
                $data['order_number'] = $driver['num'];
                $data['driver_id'] = $driver['driver_id'];
                $data['uid'] = $driver['uid'];
                $data['contents'] = $contents;
                $data['beizhu'] = $beizhu;
                $data['create_time'] = date("Y-m-d H:i:s",time());
                $add = Db::table('complaints')->insert($data);
                if($add){
                    // ratedpassengercomplaint 平台投诉表
                    $array = ['CompanyId'=>'test','OrderId'=>$driver['num'],'ComplaintTime'=>date("YmdHis",time()),'Detail'=>$contents];
                    // dump($array);
                    $news = new Curdpost();
                    $result = $news->NewInsert("ratedpassengercomplaint",$array);
                    $res = ['code'=>1000,'message'=>'提交成功!'];
                }else{
                    $res = ['code'=>1001,'message'=>'提交失败,没有数据发生变化!'];
                }
            }else{
                $res = ['code'=>1003,'message'=>'没有找到订单!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }
    // 我的钱包页面赋值
    public function mypurse(Request $request){
        $uid = $request->get('id') ? $request->get('id') : ''; //用户ID
        $data = [];
        if($uid){
            $data = Db::table('social_user')
                ->where('id','=',$uid)
                ->select("sum_money")
                ->first();
            $data = json_decode(json_encode($data),true);
            if($data){
                $res = ['code'=>1000,'message'=>'获取数据成功!','data'=>$data];
            }else{
                $res = ['code'=>1001,'message'=>'获取数据失败,没有找到要查询的数据!','data'=>$data];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!','data'=>$data];
        }
        return $res;
    }
    //余额页面赋值
    public function money(Request $request){
        $uid = $request->get('id') ? $request->get('id') : ''; //用户ID
        $data = [];
        $order = [];
        if($uid){
            $data = Db::table('social_user')
                ->where('id','=',$uid)
                ->select("sum_money")
                ->first();
            $data = json_decode(json_encode($data),true);
            $order = Db::table('order as a')
                ->join("order_price as b",'b.oid','=','a.id','left')
                ->select('b.preprice',Db::Raw('SUM(preprice) as money'))
                ->where('a.uid',$uid)
                ->whereBetween('a.implementstatus', [1, 8])
                ->first();
            $order = json_decode(json_encode($order),true);
            if(empty($order['money'])){
                $order['money'] = '0.00';
            }
            // dd($order);
            if($data){
                $res = ['code'=>1000,'message'=>'获取数据成功!','data'=>$data,'order'=>$order];
            }else{
                $res = ['code'=>1001,'message'=>'获取数据失败,没有找到要查询的数据!','data'=>$data,'order'=>$order];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!','data'=>$data,'order'=>$order];
        }
        return $res;
    }
    //按行程开发票页面列表
    public function orderlist(Request $request){
        $uid = $request->get('id');
        $phone = $request->get('phone');
        if($phone && $uid){
            // 查询已开发票的订单
            $order_list = Db::table('receipt_log')
                ->where('user_phone',$phone)
                ->get()
                ->toArray();
            $order_list = json_decode(json_encode($order_list),true);
            $fapiao_list = [];
            $newarr = [];
            $newarr = array_column($order_list, 'order_number');
            for ($i=0; $i < count($order_list); $i++) {
                $fapiao_list[$i] = explode(',', $order_list[$i]['order_number']);
            }
            $newstr = implode(',', $newarr);
            //字符串中，需要去重的数据是以数字和“，”号连接的字符串，如$str,explode()是用逗号为分割，变成一个新的数组，见打印    
            $arr = explode(',', $newstr);    
            $arr = array_unique($arr);//内置数组去重算法  算出已开发票的订单号
            // dd($arr); 
            // 查询未开发票的订单  
            $order = Db::table('order as a')
                ->join("order_price as b",'b.oid','=','a.id','left')
                // ->join("receipt_log as c",'c.order_number','=','a.num')
                ->select("a.*",'b.endprice')
                ->where('a.uid',$uid)
                ->where('a.orderstatus', 4)
                ->whereNotIn('a.num',$arr)
                ->get()
                ->toArray();
            $order = json_decode(json_encode($order),true);
            // dd($order);
            $newarr = [];
            foreach ($order as $key => $value) {
                $order[$key]['usetime'] = date("Y-m-d H:i:s",$value['usetime']);
                $order[$key]['month'] = substr($order[$key]['usetime'], 5,2).'月';
                $month = substr($order[$key]['usetime'], 5,2);
                if($month == substr($order[$key]['usetime'], 5,2)){
                    $newarr[$month.'月'][] = $order[$key];
                }
                // dd($month);
            }
            // dd($newarr);
            if($order){
                $res = ['code'=>1000,'message'=>'获取数据成功!','data'=>$newarr];
            }else{
                $res = ['code'=>1001,'message'=>'获取数据失败,没有找到要查询的数据!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }
    //按行程开发票提交
    public function fapiao_post(Request $request){
        if($request->get('id')){
            $data['user_name'] = $request->get('nickname');  //用户名称
            $data['user_phone'] = $request->get('phone');     //手机号
            $data['type'] = isset($request['type']) ? $request['type'] : false;  //类型 电子发票 或者 纸质发票
            $data['money'] = isset($request['money']) ? $request['money'] : false;  // 发票金额  
            $data['header'] = isset($request['header']) ? $request['header'] : false;  // 发票抬头
            $data['recipient'] = isset($request['recipient']) ? $request['recipient'] : false;  // 纸质发票收件人
            $data['recipient_phone'] = isset($request['recipient_phone']) ? $request['recipient_phone'] : false;  // 收件人手机号
            $data['address'] = isset($request['address']) ? $request['address'] : false;  // 收件人地址
            $data['order_number'] = isset($request['order_number']) ? $request['order_number'] : false;  // 关联订单编号 格式 : 1,2,3
            if($request->get('type')==1){
                $data['user_type'] = "个人";   // 用户身份
                $data['user_account_type'] = "个人账户";   // 账户类别
            }elseif($request->get('type')==2){
                $data['user_type'] = "企业个人";
                $data['user_account_type'] = "企业账户";
            }else{
                $data['user_type'] = "企业管理员";
                $data['user_account_type'] = "企业账户";
            }
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['status'] = 1;  //开票状态 1未开票 2已开票
            $add = Db::table('receipt_log')
                ->insert($data);
            if($add){
                $res = ['code'=>1000,'message'=>'提交成功!'];
            }else{
                $res = ['code'=>1001,'message'=>'提交失败,数据写入失败!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }

    // 已开发票列表
    public function fapiaolist(Request $request){
        //获取token里面的手机号
        if($request->get('phone')){
            $phone = $request->get('phone');
            $data = Db::table("receipt_log as a")
                // ->join('order as b','a.order_number','=','b.num')
                // ->join('server_item as c','c.id','=','b.typeid')
                ->where('user_phone',$phone)
                // ->select("a.create_time",'a.money','a.type','c.name')
                ->select("a.create_time",'a.money','a.type')
                ->get()
                ->toArray();
            $data = json_decode(json_encode($data),true);
            foreach ($data as $key => $value) {
                $data[$key]['create_time'] = substr($value['create_time'], 0,16);
            }
            if($data){
                $res = ['code'=>1000,'message'=>'获取数据成功!','data'=>$data];
            }else{
                $res = ['code'=>1001,'message'=>'获取数据失败,没有找到要查询的数据!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }
    //设置 -> 消息通知开关 1开 0关
    public function set_message(Request $request){
        $uid = $request->get('id');
        $data['push'] = $request['push'];
        if($uid){
            $user = Db::table('social_user')
                ->where('id',$uid)
                ->update($data);
            if($user){
                $res = ['code'=>1000,'message'=>'修改成功!'];
            }else{
                $res = ['code'=>1001,'message'=>'修改失败:操作数据库失败!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }

    //设置 -> 退出登录
    public function loginout(Request $request){
        $uid = $request->get('id');
        $data['token'] = null;
        $data['jpush_code'] = null;
        if($uid){
            $user = Db::table('social_user')
                ->where('id',$uid)
                ->update($data);
            if($user){
                $res = ['code'=>1000,'message'=>'退出登录成功!'];
            }else{
                $res = ['code'=>1001,'message'=>'退出登录失败,token不存在!'];
            }
        }else{
            $res = ['code'=>1002,'message'=>'参数错误!'];
        }
        return $res;
    }
}
